<template>
  <div class="filter">
    <t-drawer
      size="695px"
      :visible.sync="visible"
      :closeBtn="false"
      :close-on-overlay-click="false"
    >
      <template #header>
        <div class="drawer-head" @click="close">
          <p class="chevron-left">
            <icon-font name="chevron-left" size="18px"/>
          </p>
          <h3>{{ header }}</h3>
        </div>
      </template>
      <template #footer>
        <div class="footer-btns">
          <t-button :theme="confirmBtn.theme" :loading="confirmBtn.loading" class="" @click="handleConfirm">{{confirmBtn.text}}</t-button>
          <t-button theme="default" class="" @click="close">取消</t-button>
        </div>
      </template>
      <t-form :data="formData" :rules="rules" ref="form" label-align="top" @submit="onSubmit">
        <t-form-item label="仓库类型" name="w_type">
          <t-radio-group v-model="formData.w_type" :options="warehouseOptions"></t-radio-group>
        </t-form-item>
        <t-form-item label="名称" name="name">
          <t-input v-model="formData.name" placeholder="请输入名称"></t-input>
        </t-form-item>
        <t-form-item label="联系人" name="linkman">
          <t-input v-model="formData.linkman" placeholder="请输入联系人"></t-input>
        </t-form-item>
        <t-form-item label="电话" name="phone">
          <t-input v-model="formData.phone" :maxlength="11" placeholder="请输入电话"></t-input>
        </t-form-item>
        <t-form-item label="地区" name="province">
          <t-cascader v-model="inputValue" :input-props="inputProps" :options="formattedData" valueType="full" :show-all-levels="false" placeholder="请选择省市区" @change="changeRegion" />
        </t-form-item>
        <t-form-item label="详细地址" name="address">
          <t-input v-model="formData.address" placeholder="请输入详细地址"></t-input>
        </t-form-item>
        <t-form-item label="经纬度" name="longitude">
          <t-input-adornment style="width: 100%;" :append="changeButton">
            <t-input v-model="location" placeholder="请输入经纬度"></t-input>
          </t-input-adornment>
        </t-form-item>
        <t-form-item label="备注" name="remark">
          <t-textarea v-model="formData.remark" placeholder="请输入备注"></t-textarea>
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-radio-group v-model="formData.status" :options="statusOptions"></t-radio-group>
        </t-form-item>
      </t-form>
    </t-drawer>

    <map-container ref="map" @change="changeLocation"></map-container>
  </div>
</template>

<script lang="jsx">
import UploadImg from "@/components/upload-img/index.vue";
import { IconFont } from "tdesign-icons-vue";
import MapContainer from "@/components/MapContainer/index.vue";
import {warehouseCreateApi, warehouseDetailApi, warehouseEditApi} from "@/api/warehouse";
import provinceData from "@/config/city-data/province";
import cityData from "@/config/city-data/city";
import areaData from "@/config/city-data/area";

export default {
  name: 'WarehouseAdd',
  components: {UploadImg, IconFont, MapContainer},
  data() {
    return {
      visible: false,
      header: '添加仓库',
      confirmBtn: {
        theme: 'primary',
        text: '保存',
        loading: false
      },
      formData: {
        name: '', // 名称
        linkman: '', // 联系人
        phone: '', // 电话
        province: '', // 省
        city: '', // 市
        district: '', // 区
        address: '', // 地址
        longitude: '', // 经度
        latitude: '', // 纬度
        remark: '', // 备注
        status: 1, // 状态
        w_type: 1, // 仓库类型
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' },],
        //linkman: [{ required: true, message: '请输入联系人', trigger: 'blur' },],
        //phone: [{ required: true, message: '请输入电话', trigger: 'blur' },],
        //province: [{ required: true, message: '请选择省', trigger: 'change' },],
        //city: [{ required: true, message: '请选择市', trigger: 'change' },],
        //district: [{ required: true, message: '请选择区', trigger: 'change' },],
        //address: [{ required: true, message: '请输入详细地址', trigger: 'blur' },],
        //longitude: [{ required: true, message: '请输入经度', trigger: 'blur' },],
        //latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' },],
        //status: [{ required: true, message: '请选择状态', trigger: 'change' },],
      },
      formattedData: [],  // 地区数据
      statusOptions: [
        {label: '启用', value: 1},
        {label: '禁用', value: 0},
      ],
      warehouseOptions: [
        // （0 平台库；1 代理商库；）
        {label: '代理商库', value: 1},
        {label: '平台库', value: 0},
      ],
      location: '',
      provinceCityDistrict: '',
      inputValue: [],
      inputProps: {
        value: '',
      },
      // 查找位置按钮
      changeButton: ()=> (<t-button class="check-location" onClick={this.openMap}>地图定位</t-button>),
    }
  },
  methods: {
    // 获取省市区, 做成三级联动
    getOptions() {
      this.formattedData = this.createTree(provinceData, cityData, areaData);
    },
    createTree(provinces, cities, areas) {
      return provinces.map(province => {
        const provinceChildren = cities
          .filter(city => city.provinceCode === province.code)
          .map(city => {
            const cityChildren = areas
              .filter(area => area.cityCode === city.code)
              .map(area => ({
                label: area.name,
                value: area.code,
                cityCode: city.code,
                cityName: city.name,
                provinceCode: province.code,
                provinceName: province.name
              }));
            return {
              label: city.name,
              value: city.code,
              provinceCode: province.code,
              provinceName: province.name,
              children: cityChildren
            };
          });
        return {
          label: province.name,
          value: province.code,
          children: provinceChildren
        };
      });
    },
    changeRegion(value, context) {
      if (value?.length) {
        this.inputValue = value
        this.inputProps.value = `${context.node.data.provinceName}/${context.node.data.cityName}/${context.node.label}`
        this.formData.province = context.node.data.provinceName
        this.formData.city = context.node.data.cityName
        this.formData.district = context.node.label

        console.log('formData', this.formData)
      }
    },
    // 获取经纬度
    openMap() {
      if (this.formData.longitude && this.formData.latitude) {
        this.$refs.map.open({lng: this.formData.longitude, lat: this.formData.latitude})
        return
      }
      this.$refs.map.open({})
    },
    changeLocation({lng, lat, address, formattedAddress}) {
      this.formData.longitude = lng
      this.formData.latitude = lat
      this.formData.address = formattedAddress ? formattedAddress : address
      this.location = `${lng},${lat}`
    },
    handleConfirm() {
      this.$refs.form.submit()
    },
    onSubmit({ validateResult, firstError }) {
      if (validateResult === true) {
        this.handleSubmit()
      } else {
        this.$message.warning(firstError);
      }
    },
    handleSubmit() {
      const params = {...this.formData}
      if (this.editId) {
        params.id = this.editId
      }
      const requestApi = this.type === 'edit' ? warehouseEditApi : warehouseCreateApi
      this.confirmBtn.text = '保存中...'
      this.confirmBtn.loading = true
      requestApi(params).then(res=> {
        this.$message.success(res.retmsg)
        this.$emit('refresh')
        this.close()
      }).catch(err=> {
        console.log('err', err)
      }).finally(()=> {
        this.confirmBtn.text = '保存'
        this.confirmBtn.loading = false
      })
    },
    getDetail() {
      warehouseDetailApi(this.editId).then(res => {
        this.formData = {
          name: res.data.name, // 名称
          linkman: res.data.linkman, // 联系人
          phone: res.data.phone, // 电话
          province: res.data.province, // 省
          city: res.data.city, // 市
          district: res.data.district, // 区
          address: res.data.address, // 地址
          longitude: res.data.longitude, // 经度
          latitude: res.data.latitude, // 纬度
          remark: res.data.remark, // 备注
          status: res.data.status, // 状态
          w_type: res.data.w_type, // 仓库类型
        }

        this.inputProps = {
          value: res.data.province ? `${res.data.province}/${res.data.city}/${res.data.district}` : ''
        }

        this.location = res.data.longitude && res.data.latitude ? `${res.data.longitude},${res.data.latitude}` : ''

        if (this.type === 'edit') {
          this.header = '编辑仓库'
        }
      }).catch(err=> {
        console.log('err', err)
      })
    },
    open(type, data={}) {
      this.type = type
      this.editId = data.id
      this.header = '添加仓库'
      this.formData = {
        name: '', // 名称
        linkman: '', // 联系人
        phone: '', // 电话
        province: '', // 省
        city: '', // 市
        district: '', // 区
        address: '', // 地址
        longitude: '', // 经度
        latitude: '', // 纬度
        remark: '', // 备注
        status: 1, // 状态
        w_type: 1, // 仓库类型
      }
      if (this.type === 'edit' || this.type === 'copy') {
        this.getDetail()
      }
      this.getOptions()
      this.visible = true
    },
    close() {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
.footer-btns {
  display: flex;

  .confirm-btn {
    height: 42px;
    color: #FFFFFF;
    font-size: 16px;
    font-weight: 600;
    line-height: 22.4px;
    border-radius: var(--td-radius-medium);
  }

  .cancel-btn {
    width: 132px;
    height: 42px;
    color: #FFFFFF;
    font-size: 16px;
    font-weight: 600;
    line-height: 22.4px;
    background-color: #B8B8B8;
  }
}
</style>
